﻿using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;

namespace MetadataDesignerLibrary
{
    public class TypeReferenceRule : ILRule<TypeReferenceHandle>
    {
        [ILInfo(true)]
        public string Name { get; }

        [ILInfo(true)]
        public string Namespace { get; }

        [ILInfo]
        public EntityHandle ResolutionScope { get; }

        public TypeReferenceRule(
            EntityHandle resolutionScope,
            string @namespace,
            string name)
            : base()
        {
            ResolutionScope = resolutionScope;
            Namespace = @namespace;
            Name = name;
        }

        public TypeReferenceRule(MetadataReader reader, TypeReferenceHandle typeReferenceHandle)
            : base(reader)
        {
            TypeReference typeReference = reader.GetTypeReference(typeReferenceHandle);
            Name = reader.GetString(typeReference.Name);
            Namespace = reader.GetString(typeReference.Namespace);
            ResolutionScope = typeReference.ResolutionScope;
        }

        public override TypeReferenceHandle Write(MetadataDesigner designer)
        {
            MetadataBuilder builder = designer.Builder;
            return builder.AddTypeReference(
                resolutionScope: ResolutionScope,
                @namespace: Namespace == null ? default : builder.GetOrAddString(Namespace),
                name: Name == null ? default : builder.GetOrAddString(Name));
        }
    }
}